<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('流水号')" prop="serialNumber">
            <el-input v-model="form.serialNumber" :placeholder="$t('保存后自动生成')" show-word-limit disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开放控制')">
            <dict-select
              v-model="form.openControl"
              dictionary="open_control"
              :placeholder="$t('开放控制')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('密级')">
            <dict-select
              v-model="form.securityClassification"
              dictionary="security_classification"
              :placeholder="$t('密级')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('缓急')">
            <dict-select
              v-model="form.gradual"
              dictionary="gradual"
              :placeholder="$t('缓急')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('主送领导')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('主送领导')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('部门主管')" prop="departmentManager">
            <UserSelect v-model="form.departmentManager" :placeholder="$t('部门主管')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('签报标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('签报标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('内容概要')" prop="contentOutline">
            <el-input v-model="form.contentOutline" type="textarea" :placeholder="$t('内容概要')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('内部发送范围')" prop="internalTransmission">
            <el-input v-model="form.internalTransmission" :placeholder="$t('内部发送范围')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('可知悉的岗位或级别')" prop="canLearnPost">
            <el-input v-model="form.canLearnPost" :placeholder="$t('可知悉的岗位或级别')" show-word-limit maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('是否用印')">
            <el-radio-group v-model="form.isSeal">
              <el-radio
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('签报类型')">
            <dict-select
              v-model="form.signType"
              dictionary="sign_type"
              :placeholder="$t('签报类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联项目')" prop="dealId">
            <el-select v-model="form.dealId" multiple filterable :placeholder="$t('关联项目')" clearable>
              <el-option
                v-for="item in dealBaseList"
                :key="item.id"
                :label="item.dealName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" data-type="oa_application" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <div v-if="!btnHide" class="saveBtnAll">
        <el-button v-if="officeSwitchStatus && form.fileBase !== undefined && form.fileBase !== null" v-hasPermi="['oa:application:edit']" :disabled="isDisable" type="warning" @click="onlinePreviewOnlineEdit">{{ (form.actStatus === undefined || form.actStatus === null || form.actStatus === '') ? $t('编辑正文') : $t('查看正文') }}</el-button>
        <el-button v-if="btnShow" :style="{ 'margin-right': officeSwitchStatus && (form.fileBase === undefined || form.fileBase === null) ? '10px' : '0' }" @click="cancel()">{{ $t("取消") }}</el-button>
        <div v-if="officeSwitchStatus && (form.fileBase === undefined || form.fileBase === null)" v-hasPermi="['oa:application:edit']" style="float: left;margin-right: 15px;">
          <el-tooltip v-model="isUploadFileStatus" :manual="true" class="item" effect="dark" open-delay="3" :content="$t('请在此处上传文件')" placement="top">
            <el-dropdown trigger="click">
              <el-button type="info">
                {{ $t('正文') }}<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="officeSwitchStatus" style="text-align: center">
                  <span class="newFileClass" @click="newOpen = true; newLoading = false; createForm.fileName = ''">{{ $t('新建文件') }}</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <single
                    ref="singleRef"
                    :icon-close="false"
                    :upload-btn-name="$t('上传文件')"
                    upload-style="border: none;font-weight: 400;"
                    data-type="oa_application_zw"
                    only-suffix="docx"
                    @appendData="appendData"
                    @okPostUploadHook="okPostUploadHook"
                  />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-tooltip>
        </div>
        <el-button v-if="true" type="info" @click="showImage">{{ $t('查看流程') }}</el-button>
        <el-button v-if="btnShow" v-hasPermi="['oa:application:edit']" :disabled="isDisable" type="primary" @click="submitForm('save')">{{ $t("保存") }}</el-button>
        <el-button v-if="btnShow" v-hasPermi="['oa:application:edit']" :disabled="isDisable" type="primary" @click="submitForm('process')">{{ $t("保存并启动流程") }}</el-button>
        <el-dialog :title="$t('流程图')" :close-on-click-modal="false" :visible.sync="imageOpen" width="50%" append-to-body>
          <el-image v-if="processData.processDefinitionKey !== 'act_free_flow_approval'" v-loading="loading" :src="processData.photoBase64">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <span v-if="processData.processDefinitionKey === 'act_free_flow_approval'">
            <div style="text-align: center;margin-top: 50px;margin-bottom: 50px">
              <span v-html="$t('该功能配置流程为自由流审批<br>')" />
              <span v-html="$t('在流程启动时由流程发起人选择审批人<br>')" />
              <span v-html="$t('选择的审批人按顺序进行审批<br>')" />
            </div>
          </span>
        </el-dialog>
      </div>

      <!-- 附件预览 -->
      <OnlinePreview ref="OnlinePreview" />
      <!-- 新增 -->
      <el-dialog :title="$t('新建文件')" :visible.sync="newOpen" width="600" style="height: 350px; width: 600px; margin: auto !important;" :close-on-click-modal="false" custom-class="dialogForm" append-to-body>
        <template>
          <div v-loading="newLoading">
            <el-form ref="createForm" :model="createForm" :rules="createFormRules" label-width="120px" class="dataForm">
              <el-row>
                <el-col :span="24">
                  <el-form-item :label="$t('文件名称')" prop="fileName">
                    <el-input v-model="createForm.fileName" :placeholder="$t('文件名称')" maxlength="25">
                      <template slot="append">{{ createForm.fileSuffix }}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: right;">
              <div style="display: inline-block; margin-left: 10px;">
                <el-button @click="cancelNew">{{ $t('取消') }}</el-button>
                <el-button type="primary" @click="createWordHandle">{{ $t('新建') }}</el-button>
              </div>
            </div>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { saveOaApplication, getOaApplication } from '@/api/oa/application/oaApplication'
import { findDeal } from '@/api/base/deal/dealBase'
import { mapState } from 'vuex'
import { getSysVarValue } from '@/api/system/config'
import single from '@/components/File/Upload/single.vue'
import { createFileByProperty } from '@/api/file/fileBase'
import { showFlowChart } from '@/api/act/process/actProcess'
import { getProcessKey } from '@/api/act/process/wfMenuProcess'
export default {
  components: {
    single
  },
  data() {
    var checkFileName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(this.$t('请输入文件名称')))
      } else {
        var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,25}$/
        if (!reg.test(value)) {
          callback(new Error(this.$t('文件名不规则!')))
        } else {
          callback()
        }
      }
    }
    return {
      menuKeys: 'oa_application',
      // 流程图片是否展示
      imageOpen: false,
      // 流程数据
      processData: {},
      // 是否已经上传了文件
      isUploadFileStatus: false,
      isDisable: false,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 是否隐藏保存按钮
      btnHide: false,
      isSealOptions: [],
      openControlOptions: [],
      securityClassificationOptions: [],
      gradualOptions: [],
      signTypeOptions: [],
      actStatusOptions: [],
      dealBaseList: [],
      // 是否租用了畅写
      officeSwitchStatus: false,
      oaApplicationDealList: [],
      // 表单参数
      form: {
        // 关联项目
        oaApplicationDealList: []
      },
      // 表单校验
      rules: {
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        userId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        contentOutline: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      newLoading: false,
      newOpen: false,
      createForm: {
        templateType: undefined,
        fileName: undefined,
        fileSuffix: '.docx'
      },
      createFormRules: {
        templateType: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
        fileName: [{ required: true, validator: checkFileName, trigger: ['blur', 'change'] }]
      }
    }
  },
  computed: {
    ...mapState({
      forcedBtnHide: state => state.formBtn.forcedBtnHide
    }),
    btnShow: function() {
      // 新添加的数据 或者 流程状态 不是待审批 不是审批完成 并且当前用户是申请人 才显示保存按钮
      if (this.form.id === undefined || (this.form.actStatus !== 'D' && this.form.actStatus !== 'W' && (this.form.applyId === undefined || this.form.applyId === this.$store.state.user.userId))) {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.getDicts('open_control').then(response => {
      this.openControlOptions = response.data
    })
    this.getDicts('security_classification').then(response => {
      this.securityClassificationOptions = response.data
    })
    this.getDicts('gradual').then(response => {
      this.gradualOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.isSealOptions = response.data
    })
    this.getDicts('sign_type').then(response => {
      this.signTypeOptions = response.data
    })
    this.getDicts('work_flow_status').then(response => {
      this.actStatusOptions = response.data
    })

    findDeal().then(res => {
      this.dealBaseList = res.data
    })
    this.$bus.$emit('async_done')
  },
  mounted() {
    this.$bus.$emit('async_done')
    this.getOfficeSwitch()
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getOaApplication(data.id).then(response => {
          this.form = response.data
          this.form.oaApplicationDealList = []
          if (response.data.actStatus !== 'D' && response.data.actStatus !== 'W') {
            this.buttonShow = true
          }
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        departmentManager: undefined,
        contentOutline: undefined,
        serialNumber: undefined,
        openControl: undefined,
        securityClassification: undefined,
        gradual: undefined,
        internalTransmission: undefined,
        canLearnPost: undefined,
        isSeal: undefined,
        signType: undefined,
        dealId: undefined,
        remark: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        fileBase: undefined,
        fileList: [],
        oaApplicationDealList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      this.isDisable = true
      setTimeout(() => {
        this.isDisable = false
      }, 1000)
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            var flag = true
            if (this.officeSwitchStatus && (this.form.fileBase === undefined || this.form.fileBase === null || this.form.fileBase === '')) {
              flag = false
              this.isUploadFileStatus = true
              setTimeout(() => {
                this.isUploadFileStatus = false
              }, 1000)
            }
          }
          // 验证数据
          if (valid && flag) {
            this.loading = true
            // 保存数据
            saveOaApplication(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data
                  // 启动流程
                  this.startProcess(response.data)
                  debugger
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = 'oa_application'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/application/oaApplicationForm'
      // 业务表单打印地址
      processData.viewPath = '@/views/oa/application/oaApplicationView'
      if (this.officeSwitchStatus) {
        // 正文预览地址
        var businessPath = {}
        businessPath.name = '正文文件'
        businessPath.path = '@/views/oa/application/oaActTagOnlinePreview.vue'
        businessPath.initData = { 'fileId': (this.form.fileBase !== undefined && this.form.fileBase !== null && this.form.fileBase !== '') ? this.form.fileBase.id : '-1' }
        processData.businessPathArray = [businessPath]
      }
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKeys
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    appendData(data) {
      console.log('appendData', data)
      this.form.fileBase = { id: data.id, name: data.name }
      this.loading = false
    },
    okPostUploadHook() {
      this.loading = true
    },
    onlinePreviewOnlineEdit() {
      this.$refs.OnlinePreview.onlinePreviewFile(this.form.fileBase.id, (this.form.actStatus === null || this.form.actStatus === undefined || this.form.actStatus === '') ? 'review' : 'view')
    },
    // 判断用的是 畅写office  还是LibreOffice
    getOfficeSwitch() {
      getSysVarValue('office.changxie.enabled').then(response => {
        this.officeSwitchStatus = (response.data.office_changxie_enabled === 'true')
      })
    },
    cancelNew() {
      this.newOpen = false
      this.uploadOpen = false
    },
    /** 打开新增文件 **/
    openWordHandle() {
      this.title = this.$t('创建模板')
      this.createForm.templateType = undefined
      this.createForm.fileName = undefined
      this.uploadLoading = false
      this.newOpen = true
    },
    /** 新增空白模板文件docx */
    createWordHandle() {
      console.log('新增模板')
      this.$refs['createForm'].validate(valid => {
        if (valid) {
          this.newLoading = true
          createFileByProperty({ name: this.createForm.fileName + this.createForm.fileSuffix, dataType: 'oa_application_zw', remark: 'save' }).then(response => {
            if (response.code === 200 && response.data !== null) {
              this.msgSuccess(this.$t(response.msg))
              this.form.fileBase = response.data
            } else {
              this.msgError(this.$t('创建失败!'))
            }
            this.newOpen = false
            this.newLoading = false
          })
        }
      })
    },
    showImage() {
      this.$nextTick(() => {
        getProcessKey(this.menuKeys).then(res => {
          this.processData.processDefinitionKey = res.data
          showFlowChart(res.data).then(response => {
            this.imageOpen = true
            this.loading = true
            this.processData.photoBase64 = response.data
            this.loading = false
          })
        })
      })
    }
  }
}
</script>
